<template>
  <HeaderBar />
  <div class="outer-warp">
    <div class="w-full h-20 bg-white border-b">
      <div class="max-w-3xl mx-auto h-full flex items-center text-center">
        <n-icon size="40" class="mr-2">
          <project-icon />
        </n-icon>
        <n-text class="text-2xl"> 添加科研项目 </n-text>
      </div>
    </div>
    <div class="max-w-3xl mx-auto my-5 bg-white border p-10">
      <n-form ref="formRef" :model="projectInfo" :rules="rules">
        <n-form-item path="title" label="标题">
          <n-input v-model:value="projectInfo.title" @keydown.enter.prevent />
        </n-form-item>
        <n-form-item label="作者">
          <n-select
            v-model:value="projectInfo.authors"
            multiple
            :options="authorOptions"
            :render-label="renderLabel"
            :render-tag="renderSelectTag"
            filterable
            :on-create="hangleCreateOption"
          />
        </n-form-item>
        <n-form-item path="goal" label="简介">
          <n-input
            v-model:value="projectInfo.goal"
            maxlength="300"
            show-count
            type="textarea"
            :autosize="{
              minRows: 3
            }"
            @keydown.enter.prevent
          />
        </n-form-item>
        <div class="flex justify-end">
          <n-button type="primary" @click="submit">提交</n-button>
        </div>
      </n-form>
    </div>
  </div>
</template>

<script setup>
import HeaderBar from '@/components/common/Headerbar.vue'
import { ProjectionScreen20Regular as ProjectIcon } from '@vicons/fluent'
import api from '@/api/api'
import { NAvatar, NText, NTag } from 'naive-ui'

const router = useRouter()
const message = useMessage()

const formRef = ref(null)

const projectInfo = ref({
  title: '',
  goal: '',
  authors: []
})

const authorOptions = ref([])

const rules = {
  title: [
    {
      required: true,
      validator(rule, value) {
        if (!value) {
          return new Error('请输入标题')
        } else if (value.length > 300) {
          return new Error('标题长度应小于300字符')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ],
  goal: [
    {
      required: true,
      validator(rule, value) {
        if (!value) {
          return new Error('请输入目标')
        } else if (value.length > 300) {
          return new Error('目标长度应小于300字符')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ]
}

onMounted(() => {
  init()
})

const init = () => {
  api.User.searchInInstitution().then((res) => {
    authorOptions.value = res.data.users.map((item) => {
      return {
        label: item.name,
        value: {
          isUser: true,
          ...item
        }
      }
    })
  })
}

// 动态创建选项
const hangleCreateOption = (label) => {
  return {
    label,
    value: {
      isUser: false,
      name: label
    }
  }
}

const renderLabel = (option) => {
  return h(
    'div',
    {
      style: {
        display: 'flex',
        alignItems: 'center'
      }
    },
    [
      option.value.isUser &&
        h(NAvatar, {
          src: option.value.avatar,
          round: true,
          size: 'small'
        }),
      h(
        'div',
        {
          style: {
            marginLeft: '12px',
            padding: '4px 0'
          }
        },
        [
          h('div', null, [option.value.name]),
          h(
            NText,
            { depth: 3, tag: 'div' },
            {
              default: () => option.value.institution
            }
          )
        ]
      )
    ]
  )
}

const renderSelectTag = ({ option, handleClose }) => {
  return h(
    NTag,
    {
      style: {
        padding: '0 6px 0 4px'
      },
      round: true,
      closable: true,
      onClose: (e) => {
        e.stopPropagation()
        handleClose()
      }
    },
    {
      default: () =>
        h(
          'div',
          {
            style: {
              display: 'flex',
              alignItems: 'center'
            }
          },
          [
            option.value.isUser &&
              h(NAvatar, {
                src: option.value.avatar,
                round: true,
                size: 22,
                style: {
                  marginRight: '4px'
                }
              }),
            option.value.name
          ]
        )
    }
  )
}

// 提交
const submit = () => {
  if (projectInfo.value.authors.length === 0) {
    message.warning('请确保至少有一名参与者')
    return false
  }

  formRef.value?.validate((error) => {
    if (!error) {
      api.Project.addProject(projectInfo.value).then((res) => {
        if (res.success) {
          message.success('项目新建成功')
          router.back()
        } else {
          message.error('项目新建失败，请重试')
        }
      })
    } else {
      message.warning('请检查信息是否符合规则')
    }
  })
}
</script>

<style scoped>
.outer-warp {
  background-color: #f4f4f4;
  min-height: calc(100vh - 73px);
  overflow: auto;
}
</style>
